package com.douqu.game.battle.server;

import com.alibaba.fastjson.JSONObject;
import com.douqu.game.battle.controller.BattleController;
import com.douqu.game.battle.controller.sprite.PlayerController;
import com.douqu.game.core.e.E_NoticeType;
import com.douqu.game.core.entity.battle.BattleInitParamWorldMap;
import com.douqu.game.core.entity.world.map.ErrorEndParam;
import com.douqu.game.core.factory.ConfigFactory;
import com.douqu.game.core.factory.DataFactory;
import com.douqu.game.core.factory.FunctionFactory;
import com.douqu.game.core.protobuf.SGCommonProto;
import com.douqu.game.core.util.CoreUtils;
import com.douqu.game.core.util.LogUtils;

import java.rmi.RemoteException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Created by bean on 2017/7/27.
 */
public class WorldManager {


    private List<BattleInitInfo> battleInitInfoList = new CopyOnWriteArrayList<>();

    /**
     * key :战斗ID
     */
    private Map<String, BattleInitInfo> battleInitInfoMap = new ConcurrentHashMap<>();

    private List<PlayerController> playerList = new CopyOnWriteArrayList<>();

    private Map<String, PlayerController> playerMap = new ConcurrentHashMap<>();

    private List<BattleController> battleControllerList = new CopyOnWriteArrayList<>();

    private Map<String, BattleController> battleControllerMap = new ConcurrentHashMap<>();

//    private List<NettyConnection> connectionList = new CopyOnWriteArrayList<>();

    public void update()
    {
        if(battleControllerList.size()>100) LogUtils.warn("开始计算战斗 -> " + System.currentTimeMillis() + "  战斗数量 -> " + battleControllerList.size());
        List<String> removePlayerIndexList = new CopyOnWriteArrayList<>();
        int count = 0;
        List<ErrorEndParam> mapBattleErrorList = new CopyOnWriteArrayList<>();
        for(BattleController battleController : battleControllerList)
        {
            if(battleController.isOverdue())
            {
                LogUtils.error("WorldManager update 战斗创建后一直没有开始，删除:" + battleController);
                removePlayerIndexList.add(battleController.getSource().getObjectIndex());
                removePlayerIndexList.add(battleController.getTarget().getObjectIndex());

                removeBattleController(battleController);
            }
            else
            {
                battleController.updateCrystal();
                battleController.update(DataFactory.currentTime);
            }
            count += battleController.getSoldiers().size();
        }

        for(BattleInitInfo battleInitInfo : battleInitInfoList)
        {
            if(ConfigFactory.gmSetting.isBattleTimeoutToAI() && battleInitInfo.checkOverdueToAI())
            {
                LogUtils.error("自动处理成AI:" + battleInitInfo);
                removeBattleInitInfo(battleInitInfo);
                continue;
            }

            if(battleInitInfo.isOverdue())
            {
                //告诉对应的主服务器，没有连接战斗，如果是阵营战，则要通过阵营战服务器再去转发到主服务器
                LogUtils.error("WorldManager update 玩家一直没有来创建战斗，战斗过期删除:" + battleInitInfo);
                if(battleInitInfo.getBattleType() == SGCommonProto.E_BATTLE_TYPE.BATTLE_TYPE_WORLD_MAP)
                {
                    mapBattleErrorList.add(new ErrorEndParam(battleInitInfo.getPlayer().getPlayerIndex(), battleInitInfo.getTarget().getPlayerIndex(), (BattleInitParamWorldMap) battleInitInfo.getParam()));
                }
                else
                {
                    removePlayerIndexList.add(battleInitInfo.getPlayer().getPlayerIndex());
                    removePlayerIndexList.add(battleInitInfo.getTarget().getPlayerIndex());
                }

                removeBattleInitInfo(battleInitInfo);
            }

        }

        if(!removePlayerIndexList.isEmpty())
        {
            GameServer.getInstance().startThread(() -> {
                try {
                    GameServer.getInstance().getIMainServer().battleErrorEnd(removePlayerIndexList);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            });
        }

        if(!mapBattleErrorList.isEmpty())
        {
            GameServer.getInstance().startThread(() -> {
                try {
                    GameServer.getInstance().getIMainServer().mapBattleErrorEnd(mapBattleErrorList);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            });
        }

        if(battleControllerList.size() > 100) {
            LogUtils.warn("结束计算战斗 -> " + System.currentTimeMillis() + "  战斗数量 -> " + battleControllerList.size() + " 场上总士兵数量 -> " + count);
        }

        final long currentTime = DataFactory.currentTime;
        for(PlayerController playerController : playerList)
        {
            if(currentTime - playerController.getLastSendMsgTime() >= 60000)
            {
                LogUtils.debug("玩家->" + playerController.getName() + " 的战斗已经超过60秒没有发送消息了!");
            }
        }
    }



    public void addBattleController(BattleController battleController)
    {
        battleControllerList.add(battleController);
        battleControllerMap.put(battleController.getId(), battleController);

//        boolean addResult = false;
//        for(Integer key : battleControllerGroup.keySet())
//        {
//            addResult = battleControllerGroup.get(key).addBattleController(battleController);
//            if(addResult)
//            {
//                LogUtils.info("添加成功 -> group:" + battleControllerGroup.get(key).getGroup());
//                break;
//            }
//        }
//
//        if(!addResult)
//        {
//            BattleGroup battleGroup = new BattleGroup(battleControllerGroup.size()+1);
//            battleControllerGroup.put(battleGroup.getGroup(), battleGroup);
//            battleGroup.addBattleController(battleController);
//        }
    }

    public void removeBattleController(BattleController battleController)
    {
        battleController.destroy();

        battleControllerList.remove(battleController);
        battleControllerMap.remove(battleController.getId());
//        BattleGroup battleGroup = battleControllerGroup.get(battleController.getGroup());
//        if(battleGroup != null)
//        {
//            battleGroup.removeBattleController(battleController);
//        }
    }

    public BattleController getBattleController(String battleId)
    {
        return battleControllerMap.get(battleId);
    }



//    public void addBattleInitInfo(String battleId, SGCommonProto.E_BATTLE_TYPE battleType, E_BattleDetailType battleDetailType, String playerIndex, String targetIndex, String targetName)
//    {
//        BattleInitInfo battleInitInfo = new BattleInitInfo(battleId, battleType, battleDetailType, playerIndex, targetIndex, targetName);
//        battleInitInfoList.add(battleInitInfo);
//        battleInitInfoMap.put(battleId, battleInitInfo);
//    }

    public BattleInitInfo addBattleInitInfo(JSONObject jsonObject)
    {
        BattleInitInfo battleInitInfo = new BattleInitInfo(jsonObject);
        battleInitInfoList.add(battleInitInfo);
        battleInitInfoMap.put(battleInitInfo.getBattleId(), battleInitInfo);
        return battleInitInfo;
    }



    public void removeBattleInitInfo(BattleInitInfo battleInitInfo)
    {
        battleInitInfoList.remove(battleInitInfo);
        battleInitInfoMap.remove(battleInitInfo.getBattleId());
    }

    public BattleInitInfo getBattleInitInfo(String battleId)
    {
       return battleInitInfoMap.get(battleId);
    }


    public PlayerController getPlayerController(String playerIndex)
    {
        return playerMap.get(playerIndex);
    }


    public void dispatchGM(String notice,E_NoticeType... noticeType)
    {
        for(PlayerController playerController : playerList)
        {
            if (noticeType != null && noticeType.length > 0){
                if (noticeType[0].equals(E_NoticeType.NOTICE_TYPE_BOSS)){
                    //如果是boss推送 判断用户是否开启boss战
                    //如果等级不够不推送
                    if (!CoreUtils.isFunctionUnLock(FunctionFactory.WORLD_BOSS, playerController.getPlayer())){
                        continue;
                    }
                }
            }
            playerController.sendGM(notice);
        }
    }


    public void playerEnterGame(PlayerController playerController)
    {
        if(getPlayerController(playerController.getObjectIndex()) == null)
        {
            playerList.add(playerController);
            playerMap.put(playerController.getObjectIndex(), playerController);
        }
    }

    public void playerExitGame(PlayerController playerController)
    {
        playerController.destroy();

        playerList.remove(playerController);
        playerMap.remove(playerController.getObjectIndex());
    }


//    /**
//     * 向主服务器发送战斗数据
//     */
//    public void sendBattleData(String battleId)
//    {
//        List<BattleDetail> list = new CopyOnWriteArrayList<>();
//        if(StringUtils.isNullOrEmpty(battleId))
//        {
//
//        }
//        else
//        {
//            BattleController battleController = battleControllerMap.get(battleId);
//            if(battleController != null)
//                list.add(battleController.getBattleDetail());
//        }
//        try {
//            GameServer.getInstance().getIMainServer().sendBattleDetail(GameServer.getInstance().getId(), list);
//        } catch (RemoteException e) {
//            e.printStackTrace();
//        }
//    }

//    public void addConnection(NettyConnection connection)
//    {
//        connectionList.add(connection);
//
//        GameServer.getInstance().getWorldManager().printlnConnection();
//    }
//
//    public void removeConnection(NettyConnection connection)
//    {
//        connectionList.remove(connection);
//
//        GameServer.getInstance().getWorldManager().printlnConnection();
//    }
//
//    public void printlnConnection()
//    {
//        LogUtils.info("当前服务器连接 -> " + connectionList);
//    }
}
